#include "Scene/RenderQueue.h"

#include "Scene/Material.h"
#include "GfxDriver/GfxDriver.h"

#include <algorithm>

namespace Orca {

	//--------------------------------------------------------------------------
	RenderQueue::RenderQueue(
		  uint16 id
		, IRenderQueueSorter *sorter)
		
		: mId(id)
		, mSorter(sorter) {

	}

	//--------------------------------------------------------------------------
	RenderQueue::~RenderQueue() {

		if(mSorter)
			delete mSorter;
	}

	//--------------------------------------------------------------------------
	uint16 RenderQueue::getId() const {
		return mId;
	}

	//--------------------------------------------------------------------------
	void RenderQueue::append(
		  Material *mtl
		, RenderOperation *rop
		, float viewDist) {

		RenderSlot slot;
		slot.mtl = mtl;
		slot.rop = rop;
		slot.viewDist = viewDist;

		mSlotList.push_back(slot);
	}

	//--------------------------------------------------------------------------
	void RenderQueue::reset() {

		mSlotList.clear();
	}

	//--------------------------------------------------------------------------
	void RenderQueue::render(GfxDriver *gfxDriver) {

		_sortRenderSlotList();

		const uint32 cnt = mSlotList.size();

		// for each operation
		for(uint32 i = 0; i < cnt; ++i) {

			Material *mtl = mSlotList[i].mtl;
			RenderOperation *rop = mSlotList[i].rop;

			rop->beginRender(gfxDriver);

			uint32 passCnt = mtl->beginRender();

			// for each pass
			for(uint32 p = 0; p < passCnt; ++p) {

				mtl->beginPass(p);

				rop->render(gfxDriver);

				mtl->endPass();
			}

			mtl->endRender();

			rop->endRender(gfxDriver);
		}
	}

	//--------------------------------------------------------------------------
	void RenderQueue::_sortRenderSlotList() {

		if(!mSorter) return;

		RenderQueueCompare comp;
		comp.mSorter = mSorter;

		std::sort( mSlotList.begin(), mSlotList.end(), comp );
	}

	//--------------------------------------------------------------------------
}